﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using GS.ManagerPage;
using GS.Config;
using GS.CMS.Entities;

public partial class usercontrols_products_list : System.Web.UI.UserControl
{
    Products _Products = new Products();
    PagingPage _PagingPage = new PagingPage("products-list.aspx", "");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindData();
    }
    protected string LinkImage(object ImgPath, object ProductID, object NameProduct,object Code, object CategoryID, object Description)
    {
        string html = "";
        if (ImgPath != DBNull.Value && Description != DBNull.Value)
        {
            html += string.Format("<a href=\"product-detail.aspx?subcat={0}&pid={1}\" onmouseover=\"ddrivetip('{2} |{3}| {4}')\" onmouseout=\"hideddrivetip()\"><img alt=\"\"  src=\"{5}/{6}\" style=\"border:none\" height=\"112\" width=\"210\" /></a>",
                              CategoryID,ProductID, NameProduct,Code ,Description, Config.IamgeProduct, ImgPath);
        }
        return html;
    }
    protected string ImageStatus(object ImageName)
    {
        string html = "";
        if (ImageName != DBNull.Value)
        {
            html += string.Format("<img alt=\"\" src=\"{0}/{1}\"  /></a>",
                                   Config.Images, ImageName);
        }
        return html;
    }
    protected string ImageStock(object Quality)
    {
        string html = "";
        string strImage = "";
        if (Quality != DBNull.Value)
        {
            if ((int)Quality > 0)
                strImage = "bt_instock.jpg";
            else
                strImage = "bt_soldout.jpg";
            html += string.Format(@"<img alt='' src='{0}/{1}' width='82' height='16'  /></a>",
                                        Config.Images, strImage);
        }
        return html;
    }
    protected string LinkHeader(object ProductID, object Name, object CategoryID)
    {
        string html = "";
        if (Name != DBNull.Value)
        {
            html += string.Format(@"<a href='product-detail.aspx?subcat={0}&pid={1}' >{2}</a>",
                                  CategoryID, ProductID, Name);
        }
        return html;
    }
    protected bool IsRating(object ReviewRating)
    {
        bool isRating = false;
        if (ReviewRating != DBNull.Value && (int)ReviewRating > 0)
        {
            isRating = true;
        }
        return isRating;
    }

    /// <summary>
    /// Hiển thị kiểu giá
    /// </summary>
    /// <param name="Price"></param>
    /// <param name="IsMapPrice"></param>
    /// <param name="Discount"></param>
    /// <returns></returns>
    protected string Price(object Price, object IsMapPrice, object Discount)
    {
        string html = "";
        //Nếu có discount và Không phải là MapPirce
        if (Discount != DBNull.Value && (int)Discount > 0 && (bool)IsMapPrice == false)
        {
            if (Price != DBNull.Value)
            {
                decimal price = Convert.ToDecimal(Price);
                decimal truePrice = price - (price * (int)Discount/100);
                string[] arrPrice = truePrice.ToString("C").Split('.');
                html += string.Format("<div class=\"discount-price\"><span class=\"old-price\">{0}</span> <br/> <span class=\"new-price\">{1}<sup>.{2}</sup></span></div>",
                    price.ToString("C"), arrPrice[0], arrPrice[1]);
            }
        }
        else if ((bool)IsMapPrice == true)
        {
            if (Price != DBNull.Value)
            {
                decimal price = Convert.ToDecimal(Price);
                string[] arrPrice = price.ToString("C").Split('.');
                html += string.Format("<div class=\"map-price\">Map price <br/>{0}<sup>.{1}</sup></div>", arrPrice[0], arrPrice[1]);
            }
        }
        else if (Discount == DBNull.Value || (int)Discount == 0)
        {
            if (Price != DBNull.Value)
            {
                decimal price = Convert.ToDecimal(Price);
                string[] arrPrice = price.ToString("C").Split('.');
                html += string.Format("<div class=\"price\">{0}<sup>.{1}</sup></div>", arrPrice[0], arrPrice[1]);
            }
        }
        return html;
    }
    /// <summary>
    /// Lấy dữ liệu bind lên control DataList
    /// </summary>
    private void BindData()
    {
        try
        {
            string strStatus = Request.QueryString["root"];
            if (strStatus == null || strStatus == "new")
            {
                lblStatusProduct.Text = "New Products";
                Page.Title = "Erchobbies | New Products";
            }
            else if (strStatus == "hotdeals")
            {
                lblStatusProduct.Text = "Hot Deals";
                Page.Title = "Erchobbies | Hot Deals";
            }
            //Lấy danh sách sản phẩm
            DataSet dsStatusProduct = null;
            _PagingPage.curPage = int.Parse(Request["cp"] == null ? "1" : Request["cp"]);
            dsStatusProduct = _Products.GetListStatusProducts(strStatus, _PagingPage.curPage);
            dtlProducts.DataSource = dsStatusProduct.Tables[0];
            dtlProducts.DataBind();
            //Phân trang
            if (dsStatusProduct.Tables[0].Rows.Count > 0)
            {
                _PagingPage.SetData(dtlProducts, dsStatusProduct);
                lblPaging.Text = _PagingPage.WriteFullNav();
                lblPaging1.Text = lblPaging.Text;
            }
        }
        catch (Exception ex)
        {
            TrackingError.AddTrackingError("Author: sanghv - Funtion: BindData - Usercontrol:usercontrols_statusproducts", ex.Message);    
        }
    }
    protected void dtlProducts_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddCart"))
        {
            string strQuantity = ((TextBox)e.Item.FindControl("txtQuantity")).Text;
            if (!string.IsNullOrEmpty(strQuantity))
            {
                string Name = "", Code = "", ImageURL = "", EstimateArrival = "", CategoryID = "";
                int Discount = 0, intQuantity = 0;
                bool IsMapPrice = false;
                decimal Price = 0M;
                int ProductID = int.Parse(e.CommandArgument + "");
                //Khởi tạo session Cart
                DataTable dtCart = new DataTable();
                if (Session[Config.SessionCart] == null)
                {
                    dtCart.Columns.Add("ProductID", typeof(int));
                    dtCart.Columns.Add("Name", typeof(string));
                    dtCart.Columns.Add("Code", typeof(string));
                    dtCart.Columns.Add("Price", typeof(decimal));
                    dtCart.Columns.Add("ImageURL", typeof(string));
                    dtCart.Columns.Add("IsMapPrice", typeof(bool));
                    dtCart.Columns.Add("Quantity", typeof(int));
                    dtCart.Columns.Add("EstimateArrival", typeof(string));
                    dtCart.Columns.Add("CategoryID", typeof(string));
                }
                else
                {
                    dtCart = (DataTable)Session[Config.SessionCart];
                }
                //Lấy dữ liệu của product
                DataTable dtProduct = _Products.GetProductByIDCart(ProductID);
                if (dtProduct != null && dtProduct.Rows.Count > 0)
                {
                    //Gán biến
                    Name = dtProduct.Rows[0]["Name"] + "";
                    Code = dtProduct.Rows[0]["Code"] + "";
                    Price = (decimal)dtProduct.Rows[0]["Price"];
                    intQuantity = int.Parse(strQuantity);
                    decimal truePrice = (Price - (Price * (int)Discount / 100)) * intQuantity;
                    ImageURL = dtProduct.Rows[0]["ImageURL"] + "";
                    IsMapPrice = (bool)dtProduct.Rows[0]["IsMapPrice"];
                    EstimateArrival = dtProduct.Rows[0]["EstimateArrival"] + "";
                    CategoryID = dtProduct.Rows[0]["CategoryID"] + "";
                    foreach (DataRow row in dtCart.Rows)
                    {
                        if (ProductID == (int)row["ProductID"])
                        {
                            truePrice += (decimal)row["Price"];
                            intQuantity += (int)row["Quantity"];
                            row.Delete();
                            break;
                        }
                    }
                    //Thêm sản phẩm vào Cart
                    dtCart.Rows.Add(ProductID, Name, Code, truePrice, ImageURL, IsMapPrice, intQuantity, EstimateArrival);
                    Session[Config.SessionCart] = dtCart;
                }
                Response.Redirect("shopping-cart.aspx", true);
            }
        }
    }
}